package guoanmaker.operator.business.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

import guoanmaker.operator.business.dao.OperatorBusinessInfoDao;
import guoanmaker.operator.business.dao.OperatorProviderOrderDao;
import guoanmaker.operator.business.dao.PentAuditinfoDao;
import guoanmaker.operator.business.model.Businfo;
import guoanmaker.operator.business.model.MessageType;
import guoanmaker.operator.business.model.OperatorRefuseRecord;
import guoanmaker.operator.business.model.OperatorRefuselist;
import guoanmaker.operator.business.model.OperatorScopechange;
import guoanmaker.operator.business.model.OperatorServerClass;
import guoanmaker.operator.business.model.OperatorUser;
import guoanmaker.operator.business.model.PersonalUser;
import guoanmaker.operator.business.model.ProvideCity;
import guoanmaker.operator.business.model.ProvideCommodity;
import guoanmaker.operator.business.model.ProvideShop;
import guoanmaker.operator.business.model.ProviderBusiness;
import guoanmaker.operator.business.model.ReturnResult;
import guoanmaker.operator.business.modelnobind.BusinessServer;
import guoanmaker.operator.business.modelnobind.BusinessServiceRange;
import guoanmaker.operator.business.modelnobind.OperatorBusinessAndUser;
import guoanmaker.operator.business.modelnobind.Orderforbusiness;
import guoanmaker.operator.business.modelnobind.PendingMerchant;
import guoanmaker.operator.business.repository.MessageTypeRepository;
import guoanmaker.operator.business.repository.OperatorCityRepository;
import guoanmaker.operator.business.repository.OperatorRefuseRecordRepository;
import guoanmaker.operator.business.repository.OperatorRefuselistRepository;
import guoanmaker.operator.business.repository.OperatorScopechangeRepository;
import guoanmaker.operator.business.repository.OperatorScreenBusinessinfoRepository;
import guoanmaker.operator.business.repository.OperatorServerClassRepository;
import guoanmaker.operator.business.repository.OperatorUserRepository;
import guoanmaker.operator.business.repository.PersonalUserRepository;
import guoanmaker.operator.business.repository.ProvideAreaRepository;
import guoanmaker.operator.business.repository.ProvideCityRepository;
import guoanmaker.operator.business.repository.ProvideCommodityRepository;
import guoanmaker.operator.business.repository.ProvideCommodityServiceRangeRepository;
import guoanmaker.operator.business.repository.ProvideOrderFormRepository;
import guoanmaker.operator.business.repository.ProvideServerClassRepository;
import guoanmaker.operator.business.repository.ProvideShopRepository;
import guoanmaker.operator.business.repository.ProviderBusinessRepository;
import guoanmaker.operator.business.repository.ProviderBusinessServerRangeRepository;
import guoanmaker.operator.helper.common.abstractobj.ApiController;
import guoanmaker.operator.helper.common.util.HttpGetUtil;
import guoanmaker.operator.helper.common.util.JasyptHelper;

@Service
public class OperatorBusinessService {

	@Autowired
	private ProviderBusinessRepository providerBusinessRepository;

	@Autowired
	private ProvideCommodityRepository provideCommodityRepository;

	@Autowired
	private ProvideAreaRepository provideAreaRepository;

	@Autowired
	private ProvideCityRepository provideCityRepository;

	@Autowired
	private ProvideOrderFormRepository provideOrderFormRepository;

	@Autowired
	private ProvideServerClassRepository provideServerClassRepository;

	@Autowired
	private PersonalUserRepository personalUserRepository;

	@Autowired
	private OperatorRefuselistRepository operatorRefuselistRepository;

	@Autowired
	private OperatorRefuseRecordRepository operatorRefuseRecordRepository;
	
	@Autowired
	private OperatorServerClassRepository   operatorServerClassRepository;
	
	@Autowired
	private OperatorUserRepository  operatorUserRepository;
	
	@Autowired
	private ProvideCommodityServiceRangeRepository  provideCommodityServiceRangeRepository;
	
	
	@Autowired
	private OperatorScreenBusinessinfoRepository   operatorScreenBusinessinfoRepository;
	
	@Autowired
	private OperatorCityRepository  operatorCityRepository;
	
	@Autowired
	private ProviderBusinessServerRangeRepository  providerBusinessServerRangeRepository;
	
	@Autowired
	private OperatorProviderOrderDao    operatorProviderOrderDao;
	
	@Autowired
	private OperatorScopechangeRepository  operatorScopechangeRepository;
	
	@Autowired
	private PentAuditinfoDao pentAuditinfoDao;

	@Autowired
	private HttpServletRequest request;
	
	@Autowired
	private ProvideShopRepository  ProvideShopRepository;
	
	@Autowired
	private MessageTypeRepository  messageTypeRepository;
	
	@PersistenceContext
	private EntityManager manager;
	

	private final OperatorBusinessInfoDao operatorBusinessInfoDao;

	@Autowired
	public OperatorBusinessService(OperatorBusinessInfoDao operatorBusinessInfoDao) {
		this.operatorBusinessInfoDao = operatorBusinessInfoDao;
	}

	public OperatorBusinessInfoDao getOperatorBusinessInfoDao() {
		return operatorBusinessInfoDao;
	}



	public Workbook exportBusinessInfos(String starttime,String endtime) {
		Workbook wb = new HSSFWorkbook();
		Sheet sheet = wb.createSheet("商户信息");
		Row header = sheet.createRow(0);
		header.createCell(0).setCellValue("编号");
		header.createCell(1).setCellValue("创建时间");
		header.createCell(2).setCellValue("账号");
		header.createCell(3).setCellValue("公司名称");
		header.createCell(4).setCellValue("店铺名称");
		header.createCell(5).setCellValue("业务种类");
		header.createCell(6).setCellValue("成交率");
		header.createCell(7).setCellValue("成交笔数");
		header.createCell(8).setCellValue("交易金额");
	//	header.createCell(9).setCellValue("地区");
		header.createCell(9).setCellValue("服务地区");
		header.createCell(10).setCellValue("商品发布数");
		header.createCell(11).setCellValue("服务商状态");
		List<Businfo> list = selectByAllAccountforBusiness(starttime,endtime);
		Businfo operatorBusinessRo = new Businfo();
		for (int i = 0; i < list.size(); i++) {
			operatorBusinessRo = list.get(i);
			Row dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
			dataRow.createCell(0).setCellValue(operatorBusinessRo.getBusNumber()!=null?operatorBusinessRo.getBusNumber():"");
			if(operatorBusinessRo.getCreateDate()!=null&&!operatorBusinessRo.getCreateDate().equals("")){
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss ");
		    	String ss=	sdf.format(operatorBusinessRo.getCreateDate()); 
				dataRow.createCell(1).setCellValue(ss);
			}else{
				dataRow.createCell(1).setCellValue("");
			}
			dataRow.createCell(2).setCellValue(operatorBusinessRo.getUsername()!=null?operatorBusinessRo.getUsername():"");
			dataRow.createCell(3).setCellValue(operatorBusinessRo.getCompanyName()!=null?operatorBusinessRo.getCompanyName():"");
			dataRow.createCell(4).setCellValue(operatorBusinessRo.getBusname()!=null?operatorBusinessRo.getBusname():"");
			dataRow.createCell(5).setCellValue(operatorBusinessRo.getCommoditys()!=null?operatorBusinessRo.getCommoditys():"");
			if(operatorBusinessRo.getClosingrate()!=null){
				DecimalFormat df = new DecimalFormat("0.00%");
				String r = df.format(operatorBusinessRo.getClosingrate());
				dataRow.createCell(6).setCellValue(r);
			}else{
				dataRow.createCell(6).setCellValue("");
				
			}
			dataRow.createCell(7).setCellValue(operatorBusinessRo.getVolume()!=null?operatorBusinessRo.getVolume():0);
			dataRow.createCell(8).setCellValue(operatorBusinessRo.getTransactionAmount()!=null?operatorBusinessRo.getTransactionAmount():0);
			//dataRow.createCell(9).setCellValue(operatorBusinessRo.getCompanyCity()!=null?operatorBusinessRo.getCompanyCity():"");
			dataRow.createCell(9).setCellValue(operatorBusinessRo.getServiceAreas()!=null?operatorBusinessRo.getServiceAreas():"");
			dataRow.createCell(10).setCellValue(operatorBusinessRo.getReleasenum()!=null?operatorBusinessRo.getReleasenum():0);
			if(operatorBusinessRo.getIsProvider()!=null){
				if(operatorBusinessRo.getIsProvider().equals("2")){
					dataRow.createCell(11).setCellValue("正常");
				}else{
					dataRow.createCell(11).setCellValue("冻结");
				}
			}
		}
		return wb;
	}


   //比较两个时间相差多少分钟
	public static String getDatePoor(Date endDate, Date nowDate) {
		 
	    long nd = 1000 * 24 * 60 * 60;
	    long nh = 1000 * 60 * 60;
	    long nm = 1000 * 60;
	    // 获得两个时间的毫秒时间差异
	    long diff = endDate.getTime() - nowDate.getTime();
	    // 计算差多少分钟
	    long min = diff % nd % nh / nm;
	 
	    return  min+"";
	}
	
	
	
	/**
	 * 
	 * @param page
	 *            默认为0
	 * @param size
	 *            每页10条
	 * @param acount
	 *            商户账号
	 * @param status
	 *            状态 (所有，正常，冻结)
	 * @param volume
	 *            成交量
	 * @param volumesymbol
	 *            成交量符号 (大于，等于，小于)
	 * @param clinchadealAmount
	 *            成交金额
	 * @param clinchadealAmountsymbol
	 *            成交金额符号
	 * @param closing
	 *            成交率
	 * @param closingsymbol
	 *            成交率符号
	 * @param serverclass
	 *            服务种类
	 * @return
	 */
	public Map<String, Object> selectByAccountforBusiness(Integer page, Integer size, String acount, String status,
			Integer volume, String volumesymbol, Double clinchadealAmount, String clinchadealAmountsymbol,
			Double closing, String closingsymbol, String serverclass,String shopname,String servive) {
     String jpql="select o from Businfo o where 1=1";	
        if(StringUtils.isNotEmpty(acount)){
			jpql+=" and o.username like '%"+acount+"%'";
		}
        if(StringUtils.isNotEmpty(status)){
			if(status.equals("正常")){
				jpql+=" and o.isProvider='2'";
			}else if(status.equals("冻结")){
				jpql+=" and o.isProvider='4'";
			}else if(status.equals("所有")){
			}
		}
        if(volume!=null&&(volumesymbol!=null&&!volumesymbol.equals(""))){
			if(volumesymbol.equals("大于")){
				jpql+=" and o.volume > '"+volume+"'";
			}else if(volumesymbol.equals("等于")){
				jpql+=" and o.volume = '"+volume+"'";
			}else if(volumesymbol.equals("小于")){
				jpql+=" and o.volume < '"+volume+"'";
			}
		}
        if(clinchadealAmount!=null&&(clinchadealAmountsymbol!=null&&!clinchadealAmountsymbol.equals(""))){
			if(clinchadealAmountsymbol.equals("大于")){
				jpql+=" and o.transactionAmount > '"+clinchadealAmount+"'";
			}else if(clinchadealAmountsymbol.equals("等于")){
				jpql+=" and o.transactionAmount = '"+clinchadealAmount+"'";
			}else if(clinchadealAmountsymbol.equals("小于")){
				jpql+=" and o.transactionAmount < '"+clinchadealAmount+"'";
			}
		}
        if(closing!=null&&(closingsymbol!=null&&!closingsymbol.equals(""))){
			if(closingsymbol.equals("大于")){
				jpql+=" and o.closingrate > '"+closing+"'";
			}else if(closingsymbol.equals("等于")){
				jpql+=" and o.closingrate = '"+closing+"'";
			}else if(closingsymbol.equals("小于")){
				jpql+=" and o.closingrate < '"+closing+"'";
			}
		}
        if(StringUtils.isNotEmpty(serverclass)){
        	jpql+=" and o.companyName like '%"+serverclass+"%'";
		}
        if(StringUtils.isNotEmpty(shopname)){
        	jpql+=" and o.busname like '%"+shopname+"%'";
        }
        if(StringUtils.isNotEmpty(servive)){
        	jpql+=" and o.commoditys like '%"+servive+"%'";
		}
        if(page==null){
			page=0;
		}
		if (size==null) {
			size=10;
		}
		Query query = manager.createQuery(jpql);
		List<Businfo> result = query.getResultList();
		Map<String,Object>  map=new HashMap<>();
		map.put("total", result.size());
		query.setFirstResult(page*size);
		query.setMaxResults(size);
		List<Businfo> result1 = query.getResultList();
		if(result1.size()>0){
			for (Businfo businfo : result1) {
				String str = businfo.getCommoditys();
				if(str!=null&&!str.equals("")){
					String servername = "";
	    			List<OperatorServerClass> servers=	selectById(str);
	    			if(servers.size()>0&&servers!=null){
	    				for (OperatorServerClass operatorServerClass : servers) {
	    					servername += operatorServerClass.getServerName()+",";
	    				}
	    			}
	    			if(servers==null){
	    				 servername = "";
	    			}
					businfo.setCommoditys(servername);
				}
				if(businfo.getCompanyCity()!=null){
 					List<ProvideCity> provideCitys	= provideCityRepository.findByCode(businfo.getCompanyCity());
 					if(provideCitys.size()>0){
 						businfo.setCompanyCity(provideCitys.get(0).getName());
 					}
 				}
				
			}
		}
		map.put("businessInfos", result1);
		return map;
	}
	
	public List<Businfo> selectByAllAccountforBusiness(String starttime,String endtime)  {
        String jpql="select o from Businfo o where 1=1";	
        if (starttime != null && !starttime.equals("")) {
			jpql += " and o.createDate >='" + starttime + "'";
		}
		if (endtime != null && !endtime.equals("")) {
			jpql += " and o.createDate <='" + endtime + "'";
		}
		Query query = manager.createQuery(jpql);
		List<Businfo> result1 = query.getResultList();
		if(result1.size()>0){
			for (Businfo businfo : result1) {
				String str = businfo.getCommoditys();
				if(str!=null&&!str.equals("")){
					String servername = "";
	    			List<OperatorServerClass> servers=	selectById(str);
	    			if(servers.size()>0&&servers!=null){
	    				for (OperatorServerClass operatorServerClass : servers) {
	    					servername += operatorServerClass.getServerName()+",";
	    				}
	    			}
	    			if(servers==null){
	    				 servername = "";
	    			}
					businfo.setCommoditys(servername);
				}
				/*if(businfo.getCompanyCity()!=null){
 					List<ProvideCity> provideCitys	= provideCityRepository.findByCode(businfo.getCompanyCity());
 					if(provideCitys.size()>0){
 						businfo.setCompanyCity(provideCitys.get(0).getName());
 					}
 				}*/
				
			}
		}
		return result1;
	}
	
	
	
	
	  /** 
     * 去掉重复字符串 
     * @param str 
     * @return String  
     * */  
    public static  String removeSameString(String str){    
        Set<String> mLinkedSet = new LinkedHashSet<String>();    
        String[] strArray = str.split(",");    
        StringBuffer sb = new StringBuffer();    
        for (int i = 0; i < strArray.length; i++)    
        {    
            if (!mLinkedSet.contains(strArray[i]))    
            {    
                mLinkedSet.add(strArray[i]);    
                sb.append(strArray[i] + " ");    
            }else{  
      //          System.out.println("重复字符:"+strArray[i]);  
            }    
        }    
//        System.out.println(mLinkedSet);    
        return sb.toString().substring(0, sb.toString().length() - 1);    
    }    

	public OperatorBusinessAndUser viewmerchantinfo(String id) {
		OperatorBusinessAndUser operatorBusinessAndUser = new OperatorBusinessAndUser();
		ProviderBusiness providerBusiness = providerBusinessRepository.viewmerchantinfo(id);
		if (providerBusiness != null) {
			// -------------账号基本信息
			// 头像
			operatorBusinessAndUser.setPortrait(providerBusiness.getPersonalUser().getPortrait());
			// 账号
			operatorBusinessAndUser.setUsername(providerBusiness.getPersonalUser().getUsername());
			// 姓名
			operatorBusinessAndUser.setName(providerBusiness.getPersonalUser().getName());
			// 注册时间
			operatorBusinessAndUser.setCreateTime(providerBusiness.getPersonalUser().getCreateTime());
			// 邮箱
			operatorBusinessAndUser.setEmail(providerBusiness.getPersonalUser().getEmail());
			// 微信
			operatorBusinessAndUser.setWechat(providerBusiness.getPersonalUser().getWechat());
			// 微博
			operatorBusinessAndUser.setWeibo(providerBusiness.getPersonalUser().getWeibo());
			// 服务商
			operatorBusinessAndUser.setIsProvider(providerBusiness.getPersonalUser().getIsProvider());
			// 账号状态
			operatorBusinessAndUser.setAccountstatus(providerBusiness.getPersonalUser().getIsProvider());
			operatorBusinessAndUser.setCreateType(providerBusiness.getPersonalUser().getCreateType());
			// -------------企业基本信息
			
			operatorBusinessAndUser.setBusinessName(providerBusiness.getBusinessName());
			//编号
			operatorBusinessAndUser.setBusNumber(providerBusiness.getBusNumber());
			// 营业执照
			operatorBusinessAndUser.setCompanyLicenseReplica(providerBusiness.getCompanyLicenseReplica());
			// 企业名称
			operatorBusinessAndUser.setCompanyName(providerBusiness.getCompanyName());
			// 行业
			operatorBusinessAndUser.setCompanyindustry(providerBusiness.getCompanyindustry());
			// 证件
			operatorBusinessAndUser.setCompanyResgiserMark(providerBusiness.getCompanyResgiserMark());
			// 企业联系人
			operatorBusinessAndUser.setCompanyCorporationName(providerBusiness.getCompanyCorporationName());
			// 公司地址
			operatorBusinessAndUser.setCompanyAdress(providerBusiness.getCompanyAdress());
			// 成立时间
			operatorBusinessAndUser.setCompanyRegistTime(providerBusiness.getCompanyRegistTime());
			// 注册资本
			operatorBusinessAndUser.setCompanyRegisteredCapital(providerBusiness.getCompanyRegisteredCapital());
			// 企业规模
			operatorBusinessAndUser.setCompanyEnterpriseScale(providerBusiness.getCompanyEnterpriseScale());
			// 企业邮箱
			operatorBusinessAndUser.setCompanyEmail(providerBusiness.getCompanyEmail());
			// 前台电话
			operatorBusinessAndUser.setCompanyfrontDeskphone(providerBusiness.getCompanyfrontDeskphone());
			// 微信公众号
			operatorBusinessAndUser.setCompanyWeChatpublic(providerBusiness.getCompanyWeChatpublic());
			// 公司标记
			operatorBusinessAndUser.setCompanytag(providerBusiness.getCompanytag());
			// 服务范围
			String str = providerBusiness.getCommoditys();
				if(str!=null&&!str.equals("")){
					String servername = "";
	    			List<OperatorServerClass> servers=	selectById(str);
	    			if(servers.size()>0&&servers!=null){
	    				for (OperatorServerClass operatorServerClass : servers) {
	    					servername += operatorServerClass.getServerName()+",";
	    				}
	    			}
	    			if(servers==null){
	    				 servername = "";
	    			}
					operatorBusinessAndUser.setCommoditys(servername);
				}
			// 公司描述
			operatorBusinessAndUser.setCompanyIntroduce(providerBusiness.getCompanyIntroduce());
			
			//身份证信息
			operatorBusinessAndUser.setVoucherType(providerBusiness.getVoucherType());
			operatorBusinessAndUser.setCompanyCorporationName(providerBusiness.getCompanyCorporationName());
			operatorBusinessAndUser.setCompanyCorporationIDCardNo(providerBusiness.getCompanyCorporationIDCardNo());
			operatorBusinessAndUser.setCompanyCorporationIDCardNoFront(providerBusiness.getCompanyCorporationIDCardNoFront());
			operatorBusinessAndUser.setCompanyCorporationIDCardNoContrary(providerBusiness.getCompanyCorporationIDCardNoContrary());
		}
		return operatorBusinessAndUser;

	}

	/**
	 * 
	 * @param id
	 *            商户ID
	 * @param status
	 *            0--》消费 和 1--》接单
	 * @return
	 */
	public Map<String, Object> tradingInfo(String id,Integer status) {
	
		Map<String, Object> map = new HashMap<>();
		Double consumption = 0.0;
		Integer number = 0;
		Integer closingnumber = 0;
		Integer singledispute = 0;
		Double consumption1 = 0.0;
		Integer number1 = 0;
		Integer closingnumber1 = 0;
		Integer singledispute1 = 0;
		String  userid="";
		ProviderBusiness providerBusiness = providerBusinessRepository.findOne(id);
		if(status==1){
			if(providerBusiness!=null){
				if(providerBusiness.getPersonalUser()!=null){
					List<Orderforbusiness> listofs = operatorProviderOrderDao.selectByid(providerBusiness.getPersonalUser().getId());
					
					map.put("consumptionlist", listofs);// 订单列表
						consumption = provideOrderFormRepository.selectuserSumrRate1(providerBusiness.getPersonalUser().getId());
						if(consumption==null){
							consumption=0.0;
						}
					number = provideOrderFormRepository.selectByordernumber(providerBusiness.getPersonalUser().getId());
					closingnumber = provideOrderFormRepository.selectsucordernumber(providerBusiness.getPersonalUser().getId());
					singledispute = provideOrderFormRepository.selectSingledisputenum(providerBusiness.getPersonalUser().getId());
					userid=providerBusiness.getPersonalUser().getId();
				}
				
			}
			map.put("userid", userid);// 用户id
			map.put("consumption", consumption);// 消费
			map.put("status", 1);// 消费
			map.put("ordernumber", number);// 下单笔数
			map.put("closingnumber", closingnumber);// 下单成功
			map.put("singledispute", singledispute);// 纠纷单
		}
		 // 购买记录
		if(providerBusiness.getPersonalUser()!=null){
			List<Orderforbusiness> listofs2=	operatorProviderOrderDao.selectByidbuy(providerBusiness.getPersonalUser().getId());
			List<BusinessServer> str = new ArrayList<>();
			for (Orderforbusiness orderforbusiness : listofs2) {
				BusinessServer businessServer = new BusinessServer();
				businessServer.setServername(orderforbusiness.getServerName());
				int num=provideOrderFormRepository.selectBycountOid(providerBusiness.getPersonalUser().getId(),orderforbusiness.getServerName());
				businessServer.setNum(num);
				str.add(businessServer);
			}
			map.put("businesstype", str);// 业务分类 (购买次数)
		}
			/*List<ProvideCommodity> pcs = operatorProviderOrderDao.selectBycommid(id);
			List<BusinessServer> str = new ArrayList<>();
			int num = 0;
			if (pcs.size() > 0) {
				for (ProvideCommodity provideCommodity : pcs) {
					BusinessServer businessServer = new BusinessServer();
					businessServer.setServername(provideCommodity.getServiceType().getServerName());
					num = provideOrderFormRepository.selectBycountTotalOrder(provideCommodity.getId());
					businessServer.setNum(num);
					str.add(businessServer);
				}
			}
			map.put("businesstype", str);// 业务分类 (购买次数)
			*/
			//List<Orderforbusiness> arr=new  ArrayList<>();
			if(status==2){
				//List<ProvideCommodity> pcs1 = operatorProviderOrderDao.selectBycommid(id);
				//if(pcs1.size()>0){
					//for (ProvideCommodity provideCommodity : pcs1) {
						/*provideCommodity.setServiceRange(null);
						provideCommodity.setOrderforms(null);*/
				       
						List<Orderforbusiness> listofs1 = operatorProviderOrderDao.selectBycomid(id);
						/*if(listofs1.size()>0){
							for (Orderforbusiness provideOrderForm : listofs1) {
								
								arr.add(provideOrderForm);
							}
						}*/
						// 盈收
						Double	consumption2 = provideOrderFormRepository.selectSumrRate(id);
						if(consumption2==null){
							consumption2=0.0;
						}
						consumption1 += consumption2;
						// 接单笔数
						int	number2 = provideOrderFormRepository.selectBycountTotalOrder(id);
						number1 += number2;
						// 接单成功
						closingnumber1 = provideOrderFormRepository.selectBycountvolume(id);
						// 纠纷单、
						int	singledispute2 = provideOrderFormRepository.selectSinglebdisputenum(id);
						singledispute1 += singledispute2;
					//}
				//}
				map.put("consumptionlist1", listofs1);
				map.put("status", 2);
				map.put("consumption1", consumption1);
				map.put("ordernumber1", number1);// 下单笔数
				map.put("closingnumber1", closingnumber1);
				map.put("singledispute1", singledispute1);// 纠纷单
			}
		return map;
	}

	@Transactional
	public ReturnResult editBusinesscomInfo(String id, ProviderBusiness providerBusiness) throws UnsupportedEncodingException {
		ReturnResult returnResult = new ReturnResult();
		ProviderBusiness bu = providerBusinessRepository.findOne(id);
		if (bu != null) {
			bu.setCompanyName(providerBusiness.getCompanyName());
			bu.setBusinessName(providerBusiness.getBusinessName());
			bu.setCompanyindustry(providerBusiness.getCompanyindustry());
			bu.setCompanyRegistTime(providerBusiness.getCompanyRegistTime());
			bu.setCompanyRegisteredCapital(providerBusiness.getCompanyRegisteredCapital());
			bu.setCompanyfrontDeskphone(providerBusiness.getCompanyfrontDeskphone());
			bu.setCompanyEmail(providerBusiness.getCompanyEmail());
			bu.setCompanyEnterpriseScale(providerBusiness.getCompanyEnterpriseScale());
			bu.setCompanyWeChatpublic(providerBusiness.getCompanyWeChatpublic());
			bu.setCompanyIntroduce(providerBusiness.getCompanyIntroduce());
			bu.setCompanyLicenseReplica(providerBusiness.getCompanyLicenseReplica());
			bu.setCompanyAdress(providerBusiness.getCompanyAdress());
				if((providerBusiness.getCompanyName()!=null&&!providerBusiness.getCompanyName().equals(""))
						||(providerBusiness.getBusinessName()!=null&&!providerBusiness.getBusinessName().equals(""))){
					// 平台描述为10
					String flag = validateBusiness1(10, providerBusiness.getBusinessName(),
							providerBusiness.getCompanyName(), id);
					if (flag.equals("SUCCESS")) {
						System.out.println("编辑成功");
					}
				}
			providerBusinessRepository.save(bu);
			returnResult.setKey("success");
			returnResult.setValue("编辑成功");
		} else {
			returnResult.setKey("error");
			returnResult.setValue("编辑失败");
		}
		return returnResult;
	}
	
	public Map<String, Object> pendingMerchantList1(Integer page, Integer size, Integer status) {
		
		return  pentAuditinfoDao.selectUserinfosPage(page, size,status);
}
	
	

	public Page<ProviderBusiness> pendingMerchantList(Integer page, Integer size, Integer status) {
			Specification<ProviderBusiness> specification=new Specification<ProviderBusiness>() {
				@Override
				public Predicate toPredicate(Root<ProviderBusiness> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
					List<Predicate> lstPredicates = new ArrayList<Predicate>();
					if(status!=null){
						lstPredicates.add(criteriaBuilder.equal(root.get("personalUser").get("isProvider"), status));//等于
					}
					Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
					return criteriaBuilder.and(lstPredicates.toArray(arrayPredicates));
				}
			};
			Sort sort=null;
			if(status!=null){
				if(status==2){
					sort = new Sort(Sort.Direction.DESC, "processtime");
				}else if(status==3){
					sort = new Sort(Sort.Direction.DESC, "refusedtime");
				}else{
					sort = new Sort(Sort.Direction.DESC, "id");
				}
			}
			Pageable pageable = new PageRequest(page, size, sort);
			Page<ProviderBusiness> list=providerBusinessRepository.findAll(specification, pageable);
			if(list.getContent().size()>0){
				PersonalUser  personalUser=new PersonalUser();
				for (ProviderBusiness providerBusiness : list.getContent()) {
					// 业务类别
					
					providerBusiness.setProvideShop(null);
					
					String str = providerBusiness.getCommoditys();
					if(str!=null&&!str.equals("")){
						String servername = "";
		    			List<OperatorServerClass> servers=	selectById(str);
		    			if(servers.size()>0&&servers!=null){
		    				for (OperatorServerClass operatorServerClass : servers) {
		    					servername += operatorServerClass.getServerName()+",";
		    				}
		    			}
		    			if(servers==null){
		    				 servername = "";
		    			}
						providerBusiness.setCommoditys(servername);
					}
					personalUser=providerBusiness.getPersonalUser();
					personalUser.setPatentQueryRecords(null);
					personalUser.setTrademarks(null);
					personalUser.setOrderforms(null);
				}
				return list;
			}
			return  null;
	}
	public Map<String,Object>  pendingServicecategoryList(Integer page, Integer size, Integer status) {
		Map<String,Object>   map =new HashMap<>();
		if(status==1){
			Specification<ProviderBusiness> specification=new Specification<ProviderBusiness>() {
				@Override
				public Predicate toPredicate(Root<ProviderBusiness> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
					List<Predicate> lstPredicates = new ArrayList<Predicate>();
					if(status!=null){
						lstPredicates.add(criteriaBuilder.equal(root.get("personalUser").get("isProvider"), 2));//等于
						lstPredicates.add(criteriaBuilder.equal(root.get("serviceRange"), status));//等于
					}
					Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
					return criteriaBuilder.and(lstPredicates.toArray(arrayPredicates));
				}
			};
			Sort sort = new Sort(Sort.Direction.DESC, "id");
			Pageable pageable = new PageRequest(page, size, sort);
			Page<ProviderBusiness> list=providerBusinessRepository.findAll(specification, pageable);
			if(list.getContent().size()>0){
				PersonalUser  personalUser=new PersonalUser();
				for (ProviderBusiness providerBusiness : list.getContent()) {
					// 业务类别
					providerBusiness.setProvideShop(null);
					String str = providerBusiness.getCommoditys();
					if(str!=null&&!str.equals("")){
						String servername = "";
		    			List<OperatorServerClass> servers=	selectById(str);
		    			if(servers.size()>0&&servers!=null){
		    				for (OperatorServerClass operatorServerClass : servers) {
		    					servername += operatorServerClass.getServerName()+",";
		    				}
		    			}
		    			if(servers==null){
		    				 servername = "";
		    			}
						providerBusiness.setCommoditys(servername);
					}
					personalUser=providerBusiness.getPersonalUser();
					personalUser.setOrderforms(null);
					personalUser.setPatentQueryRecords(null);
					personalUser.setTrademarks(null);
				}
				map.put("list", list);
				return map;
			}
		}else{
			Specification<OperatorScopechange> specification=new Specification<OperatorScopechange>() {
				@Override
				public Predicate toPredicate(Root<OperatorScopechange> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
					List<Predicate> lstPredicates = new ArrayList<Predicate>();
					if(status!=null){
						lstPredicates.add(criteriaBuilder.equal(root.get("status"), status));//等于
					}
					Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
					return criteriaBuilder.and(lstPredicates.toArray(arrayPredicates));
				}
			};
			Sort sort=null;
			if(status==2){
				 sort = new Sort(Sort.Direction.DESC, "serviceProcesstime");
			}else if(status==3){
				sort = new Sort(Sort.Direction.DESC, "serviceRefusetime");
			}
			Pageable pageable = new PageRequest(page, size, sort);
			Page<OperatorScopechange> list=operatorScopechangeRepository.findAll(specification, pageable);
			if(list.getContent().size()>0){
				for (OperatorScopechange providerBusiness : list.getContent()) {
					// 业务类别
					String str = providerBusiness.getCommoditys();
					if(str!=null&&!str.equals("")){
						String servername = "";
		    			List<OperatorServerClass> servers=	selectById(str);
		    			if(servers.size()>0&&servers!=null){
		    				for (OperatorServerClass operatorServerClass : servers) {
		    					servername += operatorServerClass.getServerName()+",";
		    				}
		    			}
		    			if(servers==null){
		    				 servername = "";
		    			}
						providerBusiness.setCommoditys(servername);
					}
				}
				map.put("list", list);
				return map;
			}
		}
		map.put("list", null);
		return map;
	}

	@Transactional
	public ReturnResult auditbusiness(String id,String userid,Integer comCode) throws UnsupportedEncodingException {
		ReturnResult returnResult = new ReturnResult();
		ProviderBusiness providerBusiness = providerBusinessRepository.findOne(id);
		if (providerBusiness != null) {
			// 同意
			
			if (providerBusiness.getBusinessName() != null && providerBusiness.getCompanyName() != null) {
				// 平台描述为10
				String flag = validateBusiness(10, providerBusiness.getBusinessName(),
						providerBusiness.getCompanyName(), providerBusiness.getId(),comCode);
				if (flag.equals("SUCCESS")) {
					PersonalUser p = personalUserRepository.findOne(providerBusiness.getPersonalUser().getId());
					if (p != null) {
						p.setIsProviderTime(new Date());
						p.setIsProvider("2");
						personalUserRepository.saveAndFlush(p);
					}
					// 服务商编号规则
					// GKFAC+年（4位）+天阳日（3位，如果没有转换成月日）+时分秒
					Date date = new Date();
					Calendar ca = Calendar.getInstance();
					ca.setTime(date);
					SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
					SimpleDateFormat sdf2 = new SimpleDateFormat("hhmmss");
					String businessNumer = "";
					String year = sdf1.format(date);
					int i = ca.get(Calendar.DAY_OF_YEAR);
					String taiyangri = String.valueOf(i);
					String shifenmiao = sdf2.format(date);
					businessNumer = "GKFAC" + year + taiyangri + shifenmiao;
					providerBusiness.setBusNumber(businessNumer);
					providerBusiness.setServiceRange(2);
					providerBusiness.setProcesstime(new Date());
					providerBusinessRepository.saveAndFlush(providerBusiness);
				//记录审批记录
					OperatorRefuseRecord operatorRefuseRecord = new OperatorRefuseRecord();
					operatorRefuseRecord.setAttributId(id);
					operatorRefuseRecord.setStatus(1);
					operatorRefuseRecord.setOpchannel(0);
					operatorRefuseRecord.setRefuseTime(new Date());
					OperatorUser operatorUser = operatorUserRepository.findOne(userid);
					if (operatorUser != null) {
						operatorRefuseRecord.setUseraccountforcord(operatorUser.getUsername() + "已审批");
					}
					operatorRefuseRecordRepository.save(operatorRefuseRecord);
					//审核店铺
					List<ProvideShop> provideShops=ProvideShopRepository.findbyBusinessId(id);
					if(provideShops.size()>0){
						ProvideShop provideShop=provideShops.get(0);
						provideShop.setState(1);
						provideShop.setStateTime(new Date());
						ProvideShopRepository.saveAndFlush(provideShop);
					}
					//消息存储
					MessageType messageType=new MessageType();
					messageType.setSourceid(id);
					messageType.setCreatedate(new Date());
					messageType.setDecribestr("您有一个【"+providerBusiness.getBusinessName()+"】店铺审核已通过");
					messageType.setIsread(0);
					messageType.setType(7);
					messageType.setBusinessid(providerBusiness.getId());
					messageTypeRepository.save(messageType);
					
					returnResult.setKey("success");
					returnResult.setValue("审核成功");
				} else {
					returnResult.setKey("fail");
					returnResult.setValue("审核失败");

				}
			}
		}
		return returnResult;
	}
	
	//通过经营范围id和经营类型查询数据
		public   List<OperatorServerClass> selectByIdAndServerType(String commoditys,Integer serverType){
				List<OperatorServerClass> lists=null;
				if(StringUtils.isNotEmpty(commoditys)){
					if(commoditys.contains(",")){
						List<String> userList = Arrays.asList(commoditys.split(","));
						lists=operatorServerClassRepository.findByIdInAndServerTypeIs(userList, serverType);
					}
				}
				return lists;
			}
	//审核服务种类
	@Transactional
	public ReturnResult auditbusinessService(String id,String userid) {
		ReturnResult  returnResult=new ReturnResult();
		ProviderBusiness providerBusiness = providerBusinessRepository.findOne(id);
		if (providerBusiness != null) {
			providerBusiness.setServiceProcesstime(new Date());
			providerBusiness.setServiceRange(2);
			if(providerBusiness.getNew_commoditys()!=null){
				List<OperatorServerClass> serverClass=selectByIdAndServerType(providerBusiness.getNew_commoditys(),1);
				if(serverClass!=null){
					if(serverClass.size()>0){
						providerBusiness.setIsRoomServer(1);
					}else{
						providerBusiness.setIsRoomServer(2);
					}
				}else{
					providerBusiness.setIsRoomServer(2);
				}
				providerBusiness.setCommoditys(providerBusiness.getNew_commoditys());
			}
			ProviderBusiness providerBusiness1=	providerBusinessRepository.save(providerBusiness);
			OperatorScopechange operatorScopechange=new  OperatorScopechange();
			operatorScopechange.setBusNumber(providerBusiness1.getBusNumber());
			operatorScopechange.setCommoditys(providerBusiness1.getCommoditys());
			operatorScopechange.setCompanyName(providerBusiness1.getBusinessName());
			operatorScopechange.setBusid(providerBusiness1.getId());
			operatorScopechange.setServiceProcesstime(new Date());
			operatorScopechange.setRangeModTime(providerBusiness1.getRangeModTime());
			operatorScopechange.setStatus(2);
			if(providerBusiness1.getPersonalUser()!=null){
				operatorScopechange.setApplyuser(providerBusiness1.getPersonalUser().getUsername());
			}
			OperatorUser  operatorUser=operatorUserRepository.findOne(userid);
			if(operatorUser!=null){
				operatorScopechange.setUserrecord(operatorUser.getUsername()+"已审批通过");
				operatorScopechange.setUsername(operatorUser.getUsername());
			}
			List<BusinessServiceRange> list=	operatorProviderOrderDao.selectByServer(id);
			if(list.size()>0){
				operatorScopechange.setDel_commoditys(list.get(0).getDel_commoditys());
				operatorScopechange.setIns_commoditys(list.get(0).getIns_commoditys());
				operatorScopechange.setOld_commoditys(list.get(0).getOld_commoditys());
			}
			operatorScopechangeRepository.save(operatorScopechange);
			returnResult.setKey("success");
			returnResult.setValue("审核成功");
		}else {
			returnResult.setKey("fail");
			returnResult.setValue("审核失败");

		}
		
		return returnResult;
	}
	
	public List<OperatorServerClass> selectById(String pids) {
		List<OperatorServerClass> lists = null;
		if (StringUtils.isNotEmpty(pids)) {
			if (!pids.equals("")) {
				String[] commoditySs = pids.split(",");
				@SuppressWarnings("rawtypes")
				List twoIdList = new ArrayList();
				Collections.addAll(twoIdList, commoditySs);
				lists = operatorServerClassRepository.findByIdIn(twoIdList);
			}
		}
		return lists;
	}
	
	
	//查看服务种类变动信息
	public  Map<String, Object> selectChangeRecordandAudiet(String id,Integer status){
	    Map<String, Object>  map =new HashMap<>(); 
	    if(status!=null&&status==1){
	    	  List<BusinessServiceRange> list=	operatorProviderOrderDao.selectByServer(id);
	  	    if(list.size()>0){
	  	    	if(list.get(0).getDel_commoditys()!=null){
	  	    		       String str1= list.get(0).getDel_commoditys();
	  				    		if(str1!=null&&!str1.equals("")){
	  				    			String servername = "";
	  				    			List<OperatorServerClass> servers=	selectById(str1);
	  				    			if(servers.size()>0&&servers!=null){
	  				    				for (OperatorServerClass operatorServerClass : servers) {
	  				    					servername += operatorServerClass.getServerName()+",";
	  				    				}
	  				    			}
	  				    			if(servers==null){
	  				    				 servername = "";
	  				    			}
	  				    			list.get(0).setDel_commoditys(servername);
	  				    		}
	  	    	       }
	  	    	      if(list.get(0).getIns_commoditys()!=null){
	  	    			String str2= list.get(0).getIns_commoditys();
	  		    		if(str2!=null&&!str2.equals("")){
	  		    			String servername = "";
	  		    			List<OperatorServerClass> servers=	selectById(str2);
	  		    			if(servers.size()>0&&servers!=null){
	  		    				for (OperatorServerClass operatorServerClass : servers) {
	  		    					servername += operatorServerClass.getServerName()+",";
	  		    				}
	  		    			}
	  		    			if(servers==null){
	  		    				 servername = "";
	  		    			}
	  		    			list.get(0).setIns_commoditys(servername);
	  	    		}
	  	    	      }
	  		     	 if(list.get(0).getOld_commoditys()!=null){
	  		     		String str3= list.get(0).getOld_commoditys();
	  		    		if(str3!=null&&!str3.equals("")){
	  		    			String servername = "";
	  		    			List<OperatorServerClass> servers=	selectById(str3);
	  		    			if(servers.size()>0&&servers!=null){
	  		    				for (OperatorServerClass operatorServerClass : servers) {
	  		    					servername += operatorServerClass.getServerName()+",";
	  		    				}
	  		    			}
	  		    			if(servers==null){
	  		    				 servername = "";
	  		    			}
	  		    			list.get(0).setOld_commoditys(servername);
	  		     	}
	  		     	 }
	  		    	if(list.get(0).getNew_commoditys()!=null){
	  		    			
	  		    		String str4= list.get(0).getNew_commoditys();
	  		    		if(str4!=null&&!str4.equals("")){
	  		    			String servername = "";
	  		    			List<OperatorServerClass> servers=	selectById(str4);
	  		    			if(servers.size()>0&&servers!=null){
	  		    				for (OperatorServerClass operatorServerClass : servers) {
	  		    					servername += operatorServerClass.getServerName()+",";
	  		    				}
	  		    			}
	  		    			if(servers==null){
	  		    				 servername = "";
	  		    			}
	  		    			list.get(0).setNew_commoditys(servername);
	  		    		}
	  		    	}
	  	    		map.put("changeServerinfo", list.get(0));
	  	    	
	  	    }else{
	  	    	
	  	    	map.put("changeServerinfo", null);
	  	    }
	  	    List<OperatorRefuseRecord>   listd= operatorRefuseRecordRepository.selectByserverCategery(id);
	  		if(listd.size()>0){
	  			map.put("shenpi", listd);
	  		}else{
	  			map.put("shenpi", null);
	  		}
	    	
	    	
	    }else{
	    	OperatorScopechange  oo  =	operatorScopechangeRepository.findOne(id);
	    	BusinessServiceRange  ss=new BusinessServiceRange();
	    	if(oo!=null){
	    		if(oo.getDel_commoditys()!=null){
	    		       String str1= oo.getDel_commoditys();
	 			    		if(str1!=null&&!str1.equals("")){
	 			    			String servername = "";
	 			    			List<OperatorServerClass> servers=	selectById(str1);
	 			    			if(servers.size()>0&&servers!=null){
	 			    				for (OperatorServerClass operatorServerClass : servers) {
	 			    					servername += operatorServerClass.getServerName()+",";
	 			    				}
	 			    			}
	 			    			if(servers==null){
	 			    				 servername = "";
	 			    			}
	 			    			ss.setDel_commoditys(servername);
	 			    		}
	    	       }
	    	      if(oo.getIns_commoditys()!=null){
	    			String str2= oo.getIns_commoditys();
	 	    		if(str2!=null&&!str2.equals("")){
	 	    			String servername = "";
	 	    			List<OperatorServerClass> servers=	selectById(str2);
	 	    			if(servers.size()>0&&servers!=null){
	 	    				for (OperatorServerClass operatorServerClass : servers) {
	 	    					servername += operatorServerClass.getServerName()+",";
	 	    				}
	 	    			}
	 	    			if(servers==null){
	 	    				 servername = "";
	 	    			}
	 	    			ss.setIns_commoditys(servername);
	    		}
	    	      }
	 	     	 if(oo.getOld_commoditys()!=null){
	 	     		String str3= oo.getOld_commoditys();
	 	    		if(str3!=null&&!str3.equals("")){
	 	    			String servername = "";
	 	    			List<OperatorServerClass> servers=	selectById(str3);
	 	    			if(servers.size()>0&&servers!=null){
	 	    				for (OperatorServerClass operatorServerClass : servers) {
	 	    					servername += operatorServerClass.getServerName()+",";
	 	    				}
	 	    			}
	 	    			if(servers==null){
	 	    				 servername = "";
	 	    			}
	 	    			ss.setOld_commoditys(servername);
	 	     	}
	 	     	 }
	 	    	if(oo.getCommoditys()!=null){
	 	    			
	 	    		String str4= oo.getCommoditys();
	 	    		if(str4!=null&&!str4.equals("")){
	 	    			String servername = "";
	 	    			List<OperatorServerClass> servers=	selectById(str4);
	 	    			if(servers.size()>0&&servers!=null){
	 	    				for (OperatorServerClass operatorServerClass : servers) {
	 	    					servername += operatorServerClass.getServerName()+",";
	 	    				}
	 	    			}
	 	    			if(servers==null){
	 	    				 servername = "";
	 	    			}
	 	    			ss.setNew_commoditys(servername);
	 	    		}
	 	    	}
	    		   map.put("changeServerinfo", ss);
	    		
	    	}else{
	    		map.put("changeServerinfo", null);
	    	}
	    	List<OperatorRefuseRecord>   listd= operatorRefuseRecordRepository.selectByserverCategery(id);
	  		if(listd.size()>0){
	  			map.put("shenpi", listd);
	  		}else{
	  			map.put("shenpi", null);
	  		}
	    	
	    	
	    }
	  
		return  map;
	}
	
	
	

/*	public static void main(String[] args) {
		Date date = new Date();
		Calendar ca = Calendar.getInstance();
		ca.setTime(date);
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
		SimpleDateFormat sdf2 = new SimpleDateFormat("hhmmss");
		String businessNumer = "";
		String year = sdf1.format(date);
		int i = ca.get(Calendar.DAY_OF_YEAR);
		String taiyangri = String.valueOf(i);
		String shifenmiao = sdf2.format(date);
		businessNumer = "GKFAC" + year + taiyangri + shifenmiao;
		System.out.println(businessNumer);
	}*/

	/**
	 * 调外部审核接口
	 * 
	 * @param systemCode
	 *            平台描述
	 * @param companyName
	 *            服务商名称
	 * @param companyTitle
	 *            服务商公司名称
	 * @param originalId
	 *            服务商主键Id
	 * @param comCode    是否为内部服务商1为外部服务商，2为内部服务商
	 *            
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public static String validateBusiness(Integer systemCode, String companyName, String companyTitle,
			String originalId,Integer comCode) throws UnsupportedEncodingException {
		String a = "https://tpay.gack.citic/add_update/company?"+"systemCode=10";
		String b ="&companyName=" + URLEncoder.encode(companyName,"utf-8") + "&companyTitle=" + URLEncoder.encode(companyTitle,"utf-8") + "&originalId=" + URLEncoder.encode(originalId,"utf-8")+"&comCode="+comCode;
		String	oinfoma = HttpGetUtil.httpGet(a+b);
		System.out.println(oinfoma);
		com.alibaba.fastjson.JSONObject openidobj = JSON.parseObject(oinfoma);
		System.out.println(openidobj);
		String status = (String) openidobj.get("status");// 取出status SUCCESS
		System.out.println(status);
		return status;
	}
	/**
	 * 调外部编辑接口
	 * 
	 * @param systemCode
	 *            平台描述
	 * @param companyName
	 *            服务商名称
	 * @param companyTitle
	 *            服务商公司名称
	 * @param originalId
	 *            服务商主键Id
	 * @param comCode    是否为内部服务商1为外部服务商，2为内部服务商
	 *            
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public static String validateBusiness1(Integer systemCode, String companyName, String companyTitle,
			String originalId) throws UnsupportedEncodingException {
		String a = "https://tpay.gack.citic/add_update/company?"+"systemCode=10";
		String b ="&companyName=" + URLEncoder.encode(companyName,"utf-8") + "&companyTitle=" + URLEncoder.encode(companyTitle,"utf-8") + "&originalId=" + URLEncoder.encode(originalId,"utf-8");
		String	oinfoma = HttpGetUtil.httpGet(a+b);
		System.out.println(oinfoma);
		com.alibaba.fastjson.JSONObject openidobj = JSON.parseObject(oinfoma);
		System.out.println(openidobj);
		String status = (String) openidobj.get("status");// 取出status SUCCESS
		System.out.println(status);
		return status;
	}
	

	public ReturnResult savebusinessinfo(String businessname, String companyname) {

		ProviderBusiness providerBusiness = new ProviderBusiness();
		providerBusiness.setBusinessName(businessname);
		providerBusiness.setCompanyName(companyname);
		providerBusiness.setCompanyEnterpriseScale("22");
		providerBusinessRepository.save(providerBusiness);
		ReturnResult ReturnResult = new ReturnResult();
		ReturnResult.setKey("success");
		return ReturnResult;

	}

	@Transactional
	public PendingMerchant auditbusinessinfo(String id) {
		PendingMerchant pendingMerchant = new PendingMerchant();
		ProviderBusiness providerBusiness = providerBusinessRepository.findOne(id);
		if (providerBusiness != null) {
			// -------------账号基本信息
			pendingMerchant.setId(providerBusiness.getId());
			pendingMerchant.setBusAgelimit(providerBusiness.getBusAgelimit());
			pendingMerchant.setBusAgelimitDate(providerBusiness.getBusAgelimitDate());
			pendingMerchant.setVoucherEffectiveType(providerBusiness.getVoucherEffectiveType());
			pendingMerchant.setCompanyCorporationIDCardNoContrary(providerBusiness.getCompanyCorporationIDCardNoContrary());
			pendingMerchant.setCompanyCorporationIDCardNoFront(providerBusiness.getCompanyCorporationIDCardNoFront());
			pendingMerchant.setCompanyLicenseReplica(providerBusiness.getCompanyLicenseReplica());
			pendingMerchant.setCompanyLogo(providerBusiness.getCompanyLogo());
			pendingMerchant.setUsername(providerBusiness.getPersonalUser().getUsername());
			pendingMerchant.setName(providerBusiness.getPersonalUser().getName());
			pendingMerchant.setCreateTime(providerBusiness.getPersonalUser().getCreateTime());
			pendingMerchant.setEmail(providerBusiness.getPersonalUser().getEmail());
			pendingMerchant.setWechat(providerBusiness.getPersonalUser().getWechat());
			pendingMerchant.setWeibo(providerBusiness.getPersonalUser().getWeibo());
			pendingMerchant.setIsProvider(providerBusiness.getPersonalUser().getIsProvider());
			pendingMerchant.setAccountstatus(providerBusiness.getPersonalUser().getIsProvider());
			pendingMerchant.setCompanyName(providerBusiness.getCompanyName());
			pendingMerchant.setCompanyindustry(providerBusiness.getCompanyindustry());
			pendingMerchant.setCompanyResgiserMark(providerBusiness.getCompanyResgiserMark());
			pendingMerchant.setCompanyCorporationName(providerBusiness.getCompanyCorporationName());
			pendingMerchant.setCompanyAdress(providerBusiness.getCompanyAdress());
			pendingMerchant.setCompanyRegistTime(providerBusiness.getCompanyRegistTime());
			pendingMerchant.setCompanyRegisteredCapital(providerBusiness.getCompanyRegisteredCapital());
			pendingMerchant.setCompanyEnterpriseScale(providerBusiness.getCompanyEnterpriseScale());
			pendingMerchant.setCompanyEmail(providerBusiness.getCompanyEmail());
			pendingMerchant.setCompanyfrontDeskphone(providerBusiness.getCompanyfrontDeskphone());
			pendingMerchant.setCompanyWeChatpublic(providerBusiness.getCompanyWeChatpublic());
			pendingMerchant.setCompanytag(providerBusiness.getCompanytag());
			pendingMerchant.setBusinessName(providerBusiness.getBusinessName());
			// 业务类别
			String str = providerBusiness.getCommoditys();
			if(str!=null&&!str.equals("")){
				String servername = "";
    			List<OperatorServerClass> servers=	selectById(str);
    			if(servers.size()>0&&servers!=null){
    				for (OperatorServerClass operatorServerClass : servers) {
    					servername += operatorServerClass.getServerName()+",";
    				}
    			}
    			if(servers==null){
    				 servername = "";
    			}
				pendingMerchant.setCommoditys(servername);
			}
			pendingMerchant.setCompanyIntroduce(providerBusiness.getCompanyIntroduce());
			pendingMerchant.setBusinessName(providerBusiness.getBusinessName());
			pendingMerchant.setVoucherEffectiveDate(providerBusiness.getVoucherEffectiveDate());
			pendingMerchant.setCompanyCorporationIDCardNo(providerBusiness.getCompanyCorporationIDCardNo());

		}
		return pendingMerchant;

	}

	/**
	 * 
	 * @param id
	 *            商户Id
	 * @param content
	 *            内容
	 * @param reason
	 *            原因
	 * @return
	 */
	@Transactional
	public ReturnResult refusebusiness(String id, String content, String reason,String userid) {
		ReturnResult returnResult = new ReturnResult();
		OperatorRefuseRecord operatorRefuseRecord = new OperatorRefuseRecord();
		operatorRefuseRecord.setAttributId(id);
		operatorRefuseRecord.setReasonName(reason);
		operatorRefuseRecord.setStatus(2);
		operatorRefuseRecord.setOpchannel(0);
		operatorRefuseRecord.setContent(content);
		operatorRefuseRecord.setRefuseTime(new Date());
		OperatorUser operatorUser = operatorUserRepository.findOne(userid);
		if (operatorUser != null) {
			operatorRefuseRecord.setUseraccountforcord(operatorUser.getUsername() + "拒绝");
		}
		operatorRefuseRecordRepository.save(operatorRefuseRecord);
		ProviderBusiness providerBusiness = providerBusinessRepository.findOne(id);
		if (providerBusiness != null) {
			providerBusiness.setRefusedtime(new Date());
			providerBusinessRepository.saveAndFlush(providerBusiness);
			PersonalUser personalUser1 = personalUserRepository.findOne(providerBusiness.getPersonalUser().getId());
			personalUser1.setIsProvider("3");
			personalUserRepository.saveAndFlush(personalUser1);
			
			//消息存储
			MessageType messageType=new MessageType();
			messageType.setSourceid(id);
			messageType.setCreatedate(new Date());
			messageType.setDecribestr("您有一个【"+providerBusiness.getBusinessName()+"】店铺审核未通过");
			messageType.setIsread(0);
			messageType.setType(7);
			messageType.setBusinessid(providerBusiness.getId());
			messageTypeRepository.save(messageType);
			
		}
		//审核店铺
		List<ProvideShop> provideShops=ProvideShopRepository.findbyBusinessId(id);
		if(provideShops.size()>0){
			ProvideShop provideShop=provideShops.get(0);
			provideShop.setState(2);
			provideShop.setStateTime(new Date());
			ProvideShopRepository.saveAndFlush(provideShop);
		}
		
		returnResult.setKey("success");
		returnResult.setValue("拒绝成功");
		return returnResult;
	}
	/**
	 * 
	 * @param id
	 *            商户Id
	 * @param content
	 *            内容
	 * @param reason
	 *            原因
	 * @return
	 */
	@Transactional
	public ReturnResult refusebusinessService(String id, String content, String reason,String userid) {
		ReturnResult returnResult = new ReturnResult();
		ProviderBusiness providerBusiness = providerBusinessRepository.findOne(id);
		if (providerBusiness != null) {
			providerBusiness.setServiceRefusetime(new Date());
		    providerBusiness.setServiceRange(3);
		    ProviderBusiness providerBusiness1=	providerBusinessRepository.save(providerBusiness);
			OperatorScopechange operatorScopechange=new  OperatorScopechange();
			operatorScopechange.setBusNumber(providerBusiness1.getBusNumber());
			operatorScopechange.setCommoditys(providerBusiness1.getCommoditys());
			operatorScopechange.setCompanyName(providerBusiness1.getBusinessName());
			operatorScopechange.setRangeModTime(providerBusiness1.getRangeModTime());
			operatorScopechange.setBusid(providerBusiness1.getId());
			operatorScopechange.setServiceRefusetime(new Date());
			operatorScopechange.setStatus(3);
			operatorScopechange.setReasonname(reason);
			if(providerBusiness1.getPersonalUser()!=null){
				operatorScopechange.setApplyuser(providerBusiness1.getPersonalUser().getUsername());
			}
			OperatorUser  operatorUser=operatorUserRepository.findOne(userid);
			if(operatorUser!=null){
				operatorScopechange.setUserrecord(operatorUser.getUsername()+"已拒绝");
				operatorScopechange.setUsername(operatorUser.getUsername());
			}
			List<BusinessServiceRange> list=	operatorProviderOrderDao.selectByServer(id);
			if(list.size()>0){
				operatorScopechange.setDel_commoditys(list.get(0).getDel_commoditys());
				operatorScopechange.setIns_commoditys(list.get(0).getIns_commoditys());
				operatorScopechange.setOld_commoditys(list.get(0).getOld_commoditys());
			}
			operatorScopechangeRepository.save(operatorScopechange);
		}
		returnResult.setKey("success");
		returnResult.setValue("拒绝成功");
		return returnResult;
	}
	public List<OperatorRefuseRecord> approrecords(String id) {
		List<OperatorRefuseRecord> list = operatorRefuseRecordRepository.selectById(id);
		if (list.size() > 0) {
			return list;
		} else {
			return null;
		}
	}

	public List<OperatorRefuselist> refuseList() {
		List<OperatorRefuselist> list = operatorRefuselistRepository.selectBybusrefuse();
		if (list.size() > 0) {
			return list;
		} else {
			return null;
		}
	}
	
	public   Map<String, Object>  selectoneOrTwoServer(){
		 Map<String, Object>  map =new HashMap<>();
		 List<OperatorServerClass>  list1= operatorServerClassRepository.selectByOneServerclass();
		 if(list1.size()>0){
			 map.put("oneServerclass", list1);
		 }
		 List<OperatorServerClass>  list2= operatorServerClassRepository.selectByTwoServerclass();
		 if(list2.size()>0){
			 map.put("twoServerclass", list2);
		 }
		 return   map;
	}
	
	@Transactional
	public ReturnResult  freezebusiness(String id){
		ReturnResult returnResult=new ReturnResult();
		ProviderBusiness  providerBusines=providerBusinessRepository.findOne(id);
		if(providerBusines!=null){
			if(providerBusines.getProvideShop()!=null){
				ProvideShop provideShop=providerBusines.getProvideShop();
				provideShop.setState(3);
				ProvideShopRepository.save(provideShop);
			}
			if(providerBusines.getPersonalUser()!=null){
				PersonalUser   user=personalUserRepository.findOne(providerBusines.getPersonalUser().getId());
				if(user!=null){
					user.setIsProvider("4");
					personalUserRepository.save(user);
					returnResult.setKey("success");
					returnResult.setValue("冻结成功");
				}
			}
		//冻结服务商下的商品	
		List<ProvideCommodity> lists=	provideCommodityRepository.findbyCommditys(id);
			if(lists.size()>0){
				for (ProvideCommodity provideCommodity : lists) {
					provideCommodity.setCommodityState(8);
					provideCommodityRepository.save(provideCommodity);
				}
			}
		}
	    return 	returnResult;
	}
	@Transactional
	public ReturnResult  jihuofreezebusiness(String id){
		ReturnResult returnResult=new ReturnResult();
		ProviderBusiness  providerBusines=providerBusinessRepository.findOne(id);
		if(providerBusines!=null){
			if(providerBusines.getPersonalUser()!=null){
				PersonalUser   user=personalUserRepository.findOne(providerBusines.getPersonalUser().getId());
				if(user!=null){
					user.setIsProvider("2");
					personalUserRepository.save(user);
					returnResult.setKey("success");
					returnResult.setValue("解冻成功");
				}
			}
			if(providerBusines.getProvideShop()!=null){
				ProvideShop provideShop=providerBusines.getProvideShop();
				provideShop.setState(1);
				ProvideShopRepository.save(provideShop);
			}
			//解冻商品
			List<ProvideCommodity> lists=	provideCommodityRepository.findbyCommditystatue8(id);
			if(lists.size()>0){
				for (ProvideCommodity provideCommodity : lists) {
					provideCommodity.setCommodityState(2);
					provideCommodityRepository.save(provideCommodity);
				}
			}
		}
		return 	returnResult;
	}
	
	@Transactional
	public OperatorScopechange  Servicecategoryinfo(String id){
		OperatorScopechange operatorScopechange =operatorScopechangeRepository.findOne(id);
		return operatorScopechange;
	}
	

	@Transactional
	public int saverefuse(String refuseName) {
		OperatorRefuselist operatorRefuselist = new OperatorRefuselist();
		operatorRefuselist.setCategoryName(refuseName);
		operatorRefuselist.setCreateDate(new Date());
		operatorRefuselist.setAttribution(3);
		operatorRefuselist.setCreateUser("admin");
		operatorRefuselistRepository.save(operatorRefuselist);
		return 1;

	}
	/**
	 * 
	    * @Title: changeBusinessPassword  
	    * @Description: 根据id修改服务商密码  
	    * @param @param id
	    * @param @return      
	    * @return ReturnResult      
	    * @throws
	 */
	@Transactional
	public ReturnResult changeBusinessPassword(String id) {
		ReturnResult returnResult = new ReturnResult();
		ProviderBusiness providerBusiness = providerBusinessRepository.findOne(id);
		if (providerBusiness != null) {
			PersonalUser personalUser = providerBusiness.getPersonalUser();
			if (personalUser != null) {
				personalUser.setPassword(JasyptHelper.encrypt("CDAF26F2C15D03E4E2E724C1EBBABCF8", ApiController.PASSWORD_SALT));//明文是gack123大写加密MD5
				providerBusinessRepository.save(providerBusiness);
				returnResult.setKey("success");
				returnResult.setValue("修改成功");
			} else {
				returnResult.setKey("error");
				returnResult.setValue("用户不能为空");
			}
		} else {
			returnResult.setKey("error");
			returnResult.setValue("商户不存在");
		}
		return returnResult;
	}

}
